<template>
	<div class="login_container">
		<div class="left_box"></div>
		<div class="right_box">
			<el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
				<h1>Hello</h1>
				<h2>欢迎来到硅谷甄选</h2>
				<el-form-item style="width: 100%" prop="username">
					<el-input
						v-model="loginForm.username"
						style="width: 100%"
						:prefix-icon="User"
					/>
				</el-form-item>
				<el-form-item style="width: 100%" prop="password">
					<el-input
						v-model="loginForm.password"
						style="width: 100%"
						:prefix-icon="Lock"
						show-password
					/>
				</el-form-item>
				<el-form-item style="width: 100%">
					<el-button
						type="primary"
						:loading="isLoading"
						@click="login(loginFormRef)"
						style="width: 100%"
						>登陆</el-button
					>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>
<script lang="ts" setup name="Login">
	import type { LoginForm } from '@/api/user/type';
	import { reactive, ref } from 'vue';
	import { User, Lock } from '@element-plus/icons-vue';
	import { reqLogin } from '@/api/user';
	import router from '@/router';
	import { setToken } from '@/utils/tokenUtil';
	import { ElNotification } from 'element-plus';
	import type { FormRules, FormInstance } from 'element-plus';
	let loginForm = reactive<LoginForm>({
		username: 'admin',
		password: '111111',
	});
	let loginFormRef = ref<FormInstance>();
	let loginRules = reactive<FormRules>({
		username: [
			{
				required: true,
				message: '请输入用户名',
				trigger: 'blur',
			},
			{ min: 5, max: 10, message: '用户名长度为5-10位', trigger: 'blur' },
		],
		password: [
			{
				required: true,
				message: '请输入密码',
				trigger: 'blur',
			},
			{ min: 5, message: '密码长度最少为5位', trigger: 'blur' },
		],
	});
	let isLoading = ref(false);
	let login = async (loginFormRef: FormInstance | undefined) => {
		// 1. 是否验证成功
		if (!loginFormRef) return;
		let valid = await loginFormRef
			.validate((valid, fields) => {
				return valid ? Promise.resolve() : Promise.reject();
			})
			.catch((error) => {});
		if (!valid) return;
		// 2. 验证成功
		isLoading.value = true;
		let { code, message, data } = await reqLogin(loginForm);
		if (code == 200) {
			router.push('/');
			setToken(data as string);
			ElNotification.success({
				title: '登陆成功',
				message: '你好，欢迎回来',
				offset: 100,
			});
		} else {
			ElMessage.error({
				message: message || '',
			});
		}
		isLoading.value = false;
	};
</script>
<style scoped lang="scss">
	.login_container {
		width: 100%;
		height: 100vh;
		background-image: url(../../assets/images/background.jpg);
		background-repeat: no-repeat;
		background-size: cover;
		display: flex;
		flex-direction: row;
		div {
			width: 50%;
		}
	}
	.el-form {
		position: relative;
		top: 30%;
		background-color: #3c48bb;
		width: 80%;
		padding: 50px 40px;
		color: white;
		border-radius: 10px;
		h1 {
			margin-bottom: 18px;
		}
		h2 {
			margin-bottom: 18px;
		}
	}
</style>
